//
//  DirectoryTableViewController.m
//  DSNDialer
//
//  Created by Chris Morrell on 4/30/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "DirectoryTableViewController.h"
#import "DirectoryDetailViewController.h"
//#import "NSDictionary-MutableDeepCopy.h"
#import "PhoneBookEntry.h"


@implementation DirectoryTableViewController
@synthesize phoneBook;
@synthesize filteredPhoneBook;
@synthesize compressedPhoneBook;
@synthesize keys;
@synthesize searchBar;
@synthesize searchDC;

-(void)cancelButtonAction:(id)sender
{
	[self dismissModalViewControllerAnimated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
	[self.searchBar setText:@""];
}

-(void)searchButtonAction:(id)sender
{
	[self.searchDC setActive:YES animated:YES];
	[self.searchBar becomeFirstResponder];
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIBarButtonItem *convertButton = [[UIBarButtonItem alloc] initWithTitle:@"Home" style:UIBarButtonItemStyleDone target:self action:@selector(cancelButtonAction:)];
	self.navigationItem.leftBarButtonItem = convertButton;
	[convertButton release];
	
	UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchButtonAction:)];
	self.navigationItem.rightBarButtonItem = searchButton;
	[searchButton release];
	
	// Create a search bar
	self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	self.searchBar.tintColor = [UIColor grayColor];
	self.searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	self.searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
	self.searchBar.keyboardType = UIKeyboardTypeAlphabet;
	self.searchBar.delegate = self;
	self.tableView.tableHeaderView = self.searchBar;
	
	// Create the search display controller
	self.searchDC = [[[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self] autorelease];
	self.searchDC.searchResultsDataSource = self;
	self.searchDC.searchResultsDelegate = self;
	self.searchDC.delegate = self;
	
	NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"PhonebookABC" ofType:@"plist"];
	NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
	self.phoneBook = dict;
	[dict release];
	
	NSMutableArray *keyArray = [[NSMutableArray alloc] init];
	[keyArray addObjectsFromArray:[[self.phoneBook allKeys] sortedArrayUsingSelector:@selector(compare:)]];
	self.keys = keyArray;
	[keyArray release];
	
	[self.tableView setContentOffset:CGPointMake(0.0, 44.0) animated:NO];
	 
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	if (tableView == self.searchDisplayController.searchResultsTableView)
		return 1;
	return ([keys count] > 0) ? [keys count] : 1;
}

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
	if (tableView == self.searchDisplayController.searchResultsTableView)
		return nil;
	return keys;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
	if ([keys count] == 0 || tableView == self.searchDisplayController.searchResultsTableView)
		return nil;
	NSString *key = [keys objectAtIndex:section];
	return key;
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
	return index;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
		return [filteredPhoneBook count];
	}
	else 
	{
		NSString *key = [keys objectAtIndex:section];
		NSArray *phoneBookSection = [phoneBook objectForKey:key];
		return [phoneBookSection count];		
	}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	NSUInteger section = [indexPath section];
	NSUInteger row = [indexPath row];
	
	NSString *key = [keys objectAtIndex:section];

	NSArray *phoneBookSection = [phoneBook objectForKey:key];	
	
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
		phoneBookSection = filteredPhoneBook;		
	}

	static NSString *cellID = @"cellID";
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID] autorelease];
    }

	NSDictionary *thisEntry = [phoneBookSection objectAtIndex:row];
	cell.textLabel.text = [thisEntry objectForKey:@"sitename"];
	
	if ([[thisEntry objectForKey:@"city"] isEqualToString:@""] && 
		[[thisEntry objectForKey:@"state"] isEqualToString:@""] && 
		[[thisEntry objectForKey:@"country"] isEqualToString:@""]) 
	{
		cell.detailTextLabel.text = @"";
	}
	else if ([[thisEntry objectForKey:@"city"] isEqualToString:@""] && 
			 [[thisEntry objectForKey:@"state"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",
									 [thisEntry objectForKey:@"country"]];
	}
	else if ([[thisEntry objectForKey:@"state"] isEqualToString:@""] && 
			 [[thisEntry objectForKey:@"country"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",
									 [thisEntry objectForKey:@"city"]];
	}
	else if ([[thisEntry objectForKey:@"city"] isEqualToString:@""] && 
			 [[thisEntry objectForKey:@"country"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",
									 [thisEntry objectForKey:@"state"]];
	}
	else if ([[thisEntry objectForKey:@"city"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@",
									 [thisEntry objectForKey:@"state"],
									 [thisEntry objectForKey:@"country"]];
	}
	else if ([[thisEntry objectForKey:@"state"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@",
									 [thisEntry objectForKey:@"city"],
									 [thisEntry objectForKey:@"country"]];
	}
	else if ([[thisEntry objectForKey:@"country"] isEqualToString:@""])
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@",
									 [thisEntry objectForKey:@"city"],
									 [thisEntry objectForKey:@"state"]];
	}
	else 
	{
		cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@, %@",
									 [thisEntry objectForKey:@"city"],
									 [thisEntry objectForKey:@"state"],
									 [thisEntry objectForKey:@"country"]];
	}
    return cell;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	DirectoryDetailViewController *detailViewController = [[DirectoryDetailViewController alloc] initWithNibName:@"DirectoryDetailView" bundle:nil];
	if (tableView == self.searchDisplayController.searchResultsTableView)
	{
		detailViewController.thisPhoneBookDictionary = [self.filteredPhoneBook objectAtIndex:indexPath.row];		
	}
	else
	{
		NSString *key = [keys objectAtIndex:indexPath.section];
		detailViewController.thisPhoneBookDictionary = [[self.phoneBook objectForKey:key] objectAtIndex:indexPath.row];
	}
	
	[self.navigationController pushViewController:detailViewController animated:YES];
	[detailViewController release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self tableView:tableView titleForHeaderInSection:section] != nil) {
        return 25;
    }
    else {
        // If no section header title, no section header needed
        return 0;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    NSString *sectionTitle = [self tableView:tableView titleForHeaderInSection:section];
    if (sectionTitle == nil) {
        return nil;
    }
	
    // Create label with section title
    UILabel *label = [[[UILabel alloc] init] autorelease];
    label.frame = CGRectMake(0, 0, 320, 25);
    label.backgroundColor = [UIColor grayColor];
	label.alpha = 0.8;
    label.textColor = [UIColor whiteColor];
    label.shadowColor = [UIColor lightGrayColor];
    label.shadowOffset = CGSizeMake(0.0, -1.0);
    label.font = [UIFont boldSystemFontOfSize:16];
    label.text = [NSString stringWithFormat:@" %@",sectionTitle];
	
    // Create header view and add label as a subview
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 25)] autorelease];
    [view addSubview:label];

    return view;
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	self.searchBar = nil;
}

- (void)dealloc {
    [super dealloc];
	[phoneBook release];
	[filteredPhoneBook release];
	[compressedPhoneBook release];
	[keys release];
	[searchBar release];
	[searchDC release];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
	self.filteredPhoneBook = [NSMutableArray arrayWithCapacity:0];
	NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(SELF.sitename contains[cd] %@) OR (SELF.city contains[cd] %@) OR (SELF.state contains[cd] %@) OR (SELF.country contains[cd] %@) OR (SELF.dsn contains[cd] %@) OR (SELF.comm contains[cd] %@)",searchText,searchText,searchText,searchText,searchText,searchText];
		self.filteredPhoneBook = [self.compressedPhoneBook filteredArrayUsingPredicate:predicate];
}

#pragma mark -
#pragma mark Search Display Delegate Methods

- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
	self.compressedPhoneBook = [NSMutableArray arrayWithCapacity:0];
//	[self.compressedPhoneBook removeAllObjects];
	for (NSString *key in keys)
	{
		NSArray *array = [[NSArray alloc] initWithArray:[phoneBook objectForKey:key]];
		for (NSDictionary *entry in array)
		{
			[self.compressedPhoneBook addObject:entry];
		}
		[array release];
	}	
}

@end

